package thu.sorit.resolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;

public class TudouResolver implements Resolver {

	@Override
	public boolean owns(String url) {
		return url.contains("tudou.com");
	}

	@Override
	public Video fillVideo(String url) {
		Video v = new Video();
		v.url = url;
		try {
			Element body = Jsoup.connect(url).get().body();
			String script = body.getElementsByTag("script").first().html();
			int s = script.indexOf("pic:") + 6;
			int e = script.indexOf("'", s);
			v.preview = Util.getBitmapFromURL(script.substring(s, e));
			s = script.indexOf("time:") + 7;
			e = script.indexOf("'", s);
			v.duration = Util.timeToDuration(script.substring(s, e));
			s = script.indexOf("kw:") + 5;
			e = script.indexOf("'", s);
			v.title = script.substring(s, e);
			s = script.indexOf("iid:") + 5;
			e = script.indexOf(" ", s);
			int iid = Integer.parseInt(script.substring(s, e));
			Document d = Jsoup.connect("http://v2.tudou.com/v?it=" + iid).get();
			v.cdn = d.getElementsByTag("f").first().html();
		} catch (Exception e) {
		}
		return v;
	}

	@Override
	public List<Video> search(String keyword, Bitmap preview, int duration,
			double threshold) {
		ArrayList<Video> ret = new ArrayList<Video>();
		try {
			Log.i("peterfff", "Searching http://www.soku.com/t/nisearch/" + keyword);
			Document doc = Jsoup.connect("http://www.soku.com/t/nisearch/" + keyword).get();
			Elements eles = doc.body().getElementsByClass("pic");
			for (Element e : eles) {
				int d = Util.timeToDuration(e.getElementsByClass("vinf").first().html());
				double t = 1 - Math.abs(d - duration) / (double) duration;
				if (t < 0.95) {
					Log.i("peterfff", "drop one because of duration");
					continue;
				}
				Bitmap b = Util.getBitmapFromURL(e.getElementsByTag("img").first().attr("src"));
				double s = Util.getBitmapSimilarity(preview, b);
				b.recycle();
				if (t / 2 + s / 2 > threshold) {
					Log.i("peterfff", "find one in tudou");
					ret.add(fillVideo(e.getElementsByTag("a").first().attr("href")));
				} else {
					Log.i("peterfff", "drop one because s = " + s);
				}
			}
		} catch (IOException e1) {
		}
		return ret;
	}

}
